import re
import datetime

region = []

class tools:
    '''剔除空白行'''
    def filter_blank_line(file):
        with open(file, 'r') as f:
            lines = f.readlines()
        res = []
        for line in lines:
            if line != '\n':
                res.append(line)
        with open(file, 'w') as f:
            f.write(''.join(res))

    def formater(file):
        with open(file, 'r', encoding='UTF-8') as b:
            c = b.read()

        region = re.findall(r'(\n.*?区)\n.*?分别居住于：\n+(.*?)\n+已对相关?', c, re.DOTALL)
        # content = re.findall(r'居住于：(.*)?已对相关', c, re.M)
        print(len(region), region)

        newc = tools.parse(c, region)
        newc = re.sub('分别居住于：', '分别：', newc)
        with open(file, 'w') as f:
            f.write(newc)

    def parse(content, region):
        olds = []
        news = []
        for s in region:
            name, value = s
            if name.find('浦东新区') > -1:
                name = name[name.find('浦东新区'):]
            name = re.sub('\n', '', name)
            print(name)
            olds = value.split('\n')
            for val in olds:
                repstr = '居住于'+val if val.find('区') > -1 else '居住于{}{}'.format(name, val)
                print(val, repstr)
                content = re.sub(val, repstr, content)
        return content

yestoday = str(datetime.date.today() + datetime.timedelta(-1))
file = r'./shanghai/{}.txt'.format(yestoday.replace('-',''))
print(file)
tools.filter_blank_line(file)
tools.formater(file)
